package com.lmm.cg.zjgcg.service;

import android.Manifest;
import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.igexin.download.DownloadService;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.notification.FileDownloadNotificationHelper;
import com.lmm.cg.zjgcg.R;
import com.lmm.dresswisdom.lmmframe.retrofit.AppClient;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 下载服务
 */
public class DownloadAppService extends IntentService {

    String apkUrl = "";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYYMMDDhhmmss");
    String filePath = Environment.getExternalStorageDirectory() + File.separator + "cgDownload" + File.separator +  simpleDateFormat.format(new Date()) +  "cg.apk";

    public DownloadAppService() {
        super("downloadService");
        LogUtils.write(filePath);
        if (!new File(Environment.getExternalStorageDirectory() + File.separator + "cgDownload").exists()) {
            new File(Environment.getExternalStorageDirectory() + File.separator + "cgDownload").mkdirs();
        }
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        apkUrl = intent.getStringExtra("downloadUrl");
        FileDownloader.setup(this);
        downLoadApp();

    }

    private void downLoadApp() {
        FileDownloader.getImpl().create(apkUrl)
                .setPath(filePath)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.write("pending");
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        LogUtils.write("connected");
                        EventBus.getDefault().post(new UpdateAppMessage(0, totalBytes, 0));
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        EventBus.getDefault().post(new UpdateAppMessage(1, totalBytes, soFarBytes));
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                        LogUtils.write("blockComplete");
                        EventBus.getDefault().post(new UpdateAppMessage(2, 0, 0));

                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                        LogUtils.write("retry");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        LogUtils.write("complete");
                        // 开始安装
                        UpdateAppMessage updateAppMessage = new UpdateAppMessage(3, 0, 0);
                        updateAppMessage.setFilePath(filePath);
                        EventBus.getDefault().post(updateAppMessage);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        LogUtils.write("paused");
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        LogUtils.write("error:" + e.getLocalizedMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        LogUtils.write("warn:");
                    }
                }).start();
    }

    private void install(String filePath) {
        LogUtils.write("开始执行安装: " + filePath);
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.write("版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    DownloadAppService.this
                    , "com.lmm.cg.zjgcg.fileprovider"
                    , apkFile);
//            ActivityCompat.requestPermissions( , new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 10010);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

        } else {
            LogUtils.write("正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

}
